<template>
  <!-- fullscreen: 全屏显示 -->
  <el-dialog fullscreen @close="reset" :title="goodsData.id>0?'编辑':'新增'" :visible.sync="info.isShow">
    <el-form
      ref="goodsForm"
      label-width="80px"
      :model="goodsData"
      :rules="rules"
    >
      <el-tabs v-model="activeName">
        <el-tab-pane label="基础信息" name="first">
          <el-form-item label="一级分类" prop="first_cateid">
            <el-select
              @change="firstCateChange"
              v-model="goodsData.first_cateid"
              placeholder="请选择"
            >
              <el-option value="" label="请选择"></el-option>
              <el-option
                :value="item.id"
                v-for="item in cateList"
                :key="item.id"
                :label="item.catename"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="二级分类" prop="second_cateid">
            <el-select v-model="goodsData.second_cateid" placeholder="请选择">
              <el-option value="" label="请选择"></el-option>
              <el-option
                v-for="item in secondCateList"
                :key="item.id"
                :value="item.id"
                :label="item.catename"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品名称" prop="goodsname">
            <el-input
              v-model="goodsData.goodsname"
              placeholder="商品名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="零售价格" prop="price">
            <el-input
              placeholder="零售价格"
              v-model="goodsData.price"
            ></el-input>
          </el-form-item>
          <el-form-item label="市场价格" prop="market_price">
            <el-input
              placeholder="市场价格"
              v-model="goodsData.market_price"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品图片" prop="img">
            <el-upload
              ref="upload"
              :file-list="imgList"
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :limit="1"
              :on-exceed="limitTips"
              :on-change="imgChange"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品规格" prop="specsid">
            <el-select
              @change="specsChange"
              v-model="goodsData.specsid"
              placeholder="请选择"
            >
              <el-option
                v-for="item in specsList"
                :key="item.id"
                :value="item.id"
                :label="item.specsname"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="规格属性" prop="specsattr">
            <!-- multiple: 多选 -->
            <el-select
              v-model="goodsData.specsattr"
              placeholder="请选择"
              multiple
            >
              <el-option
                v-for="(item, index) in specsAttr"
                :key="index"
                :value="item"
                :label="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否新品" prop="isnew">
            <el-tooltip
              :content="goodsData.isnew === 1 ? '是' : '否'"
              placement="top"
            >
              <el-switch
                v-model="goodsData.isnew"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="是否热卖" prop="ishot">
            <el-tooltip
              :content="goodsData.ishot === 1 ? '是' : '否'"
              placement="top"
            >
              <el-switch
                v-model="goodsData.ishot"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="商品状态" prop="status">
            <el-radio-group v-model="goodsData.status">
              <el-radio :label="1">正常</el-radio>
              <el-radio :label="2">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品介绍" name="second">
          <!-- 富文本编辑器 -->
          <el-form-item label="商品介绍" prop="description">
            <wangeditor
              ref="editor"
              v-model="goodsData.description"
              id="description"
              width="100%"
              height="480"
            />
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="reset">取消</el-button>
      <el-button type="primary" @click="submit">提交</el-button>
    </div>
  </el-dialog>
</template>

<script>
const initData = {
  first_cateid: "", // 一级分类id
  second_cateid: "", // 二级分类id
  goodsname: "", // 商品名称
  price: "", // 商品价格
  market_price: "", // 市场价格
  img: null, // 商品图片
  specsid: "", // 商品规格
  specsattr: [], // 规格属性
  isnew: 0, // 是否新品
  ishot: 0, // 是否热卖
  status: "", // 状态
  description: "", // 商品介绍
};
// 导入vuex辅助函数
import { mapActions, mapState } from "vuex";
// 导入vue-wangeditor
import wangeditor from "vue-wangeditor";
export default {
  components: { wangeditor },
  computed: {
    ...mapState("cate", ["cateList"]),
    ...mapState("specs", ["specsList"]),
  },
  props: ["info"],
  data() {
    // 自定义表单校验函数
    const validDesc = (rule, value, callback) => {
      if (this.$refs.editor.getHtml() === "<p><br></p>") {
        this.$message.error("请输入商品介绍");
        return callback(new Error("请输入商品介绍"));
      }
      // 表单校验通过
      callback();
    };

    return {
      // 商品图片列表
      imgList:[],
      // 规格属性可选值
      specsAttr: [],
      // 保存二级分类信息
      secondCateList: [],
      // 和表单进行绑定的数据对象
      goodsData: {
        ...initData,
      },
      // 表单校验规则
      rules: {
        first_cateid: { required: true, message: "请选择", trigger: "blur" },
        second_cateid: { required: true, message: "请选择", trigger: "blur" },
        goodsname: { required: true, message: "请填写", trigger: "blur" },
        price: { required: true, message: "请填写", trigger: "blur" },
        market_price: { required: true, message: "请填写", trigger: "blur" },
        isnew: { required: true, message: "请选择", trigger: "blur" },
        ishot: { required: true, message: "请选择", trigger: "blur" },
        status: { required: true, message: "请选择", trigger: "blur" },
        specsid: { required: true, message: "请选择", trigger: "blur" },
        specsattr: { required: true, message: "请选择", trigger: "blur" },
        description: { validator: validDesc, trigger: "blur" },
      },
      // 指定默认需要展示的标签页的名字
      activeName: "first",
    };
  },
  methods: {
    ...mapActions("cate", ["getCateListAction"]),
    ...mapActions("specs", ["getSpecsListAction"]),
    // 设置表单元素的值
    setFormData(obj) {
      // 更新和表单元素绑定的数据
      this.goodsData = { ...obj };
      // 删除多余属性
      delete this.goodsData.firstcatename;
      delete this.goodsData.secondcatename;
      // 手动调用一级分类下拉框change事件处理函数
      this.firstCateChange(obj.first_cateid,false);
      // 手动调用规格下拉框change事件处理函数
      this.specsChange(obj.specsid);
      // 将规格属性可选值转换成数组格式
      this.goodsData.specsattr=obj.specsattr.split(',');
      // 设置upload图片上传组件默认需要展示的图片
      this.imgList=obj.img!==''?[{url:this.$baseUrl+obj.img}]:[];
      // 手动设置富文本编辑器默认内容
      setTimeout(()=>{
        this.$refs.editor.setHtml(obj.description);
      },200);
    },
    submit() {
      this.$refs.goodsForm.validate((valid) => {
        if (valid) {
          // 手动获取富文本编辑器的内容
          this.goodsData.description = this.$refs.editor.getHtml();
          // this.goodsData =>  FormData
          const fd = new FormData();
          for (let key in this.goodsData) {
            fd.append(key, this.goodsData[key]);
          }
          const url=this.goodsData.id>0?'/goodsedit':'/goodsadd'
          this.$axios.post(url, fd).then((res) => {
            if (res.code === 200) {
              this.$message.success(res.msg);
              // 更新数据: 通知父组件更新数据
              this.$emit("goodsUpdate");
              // 数据重置
              this.reset();
            } else {
              this.$message.error(res.msg);
            }
          });
        }
      });
    },
    // 监听用户选择图片的行为
    imgChange(file) {
      // 手动同步数据
      this.goodsData.img = file.raw;
    },
    // 一级分类下拉框change事件处理函数
    // 选中的一级分类id; flag=true表示用户通过鼠标点击重新选择一级分类, flag=false表示组件加载的时候
    firstCateChange(id,flag=true) {
      // 1-根据一级分类id查找一级分类索引
      const index = this.cateList.findIndex((item) => item.id === id);
      // 2-更新secondCateList
      if (this.cateList[index].children) {
        this.secondCateList = this.cateList[index].children;
      } else {
        this.secondCateList = [];
      }
      // 重置和二级分类下拉框绑定的数据: 当通过鼠标点击重新选择了一级分类的时候, 才需要做二级分类id的重置
      if(flag){
        this.goodsData.second_cateid = "";
      }
    },
    // 规格下拉框change事件处理函数
    specsChange(id) {
      // 1-根据id查找索引
      const index = this.specsList.findIndex((item) => item.id === id);
      // 2-根据索引获取规格属性可选值
      // 清空规格属性可选值下拉框中之前的选择
      this.goodsData.specsattr = [];
      this.specsAttr = this.specsList[index].attrs;
    },
    // 取消按钮点击事件处理函数
    reset() {
      // 关闭对话框组件
      this.info.isShow = false;
      // 重置表单元素
      this.goodsData = {
        ...initData,
      };
      // 手动重置upload组件
      this.$refs.upload.clearFiles();
      // 手动重置富文本编辑器的内容
      this.$refs.editor.setHtml("");
    },
    // 商品图片数量超出限制的提示
    limitTips() {
      this.$message.warning("此处只能选择一张图片");
    },
  },
  created() {
    //  请求商品分类列表
    this.getCateListAction();
    // 请求规格列表
    this.getSpecsListAction({ page: 1, size: 100 });
  },
};
</script>

<style>
.wangEditor-container {
  height: 400px !important;
}
</style>